package eaa.tgi.scrum.controllers;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.tomcat.util.http.fileupload.DiskFileUpload;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import eaa.tgi.scrum.constants.ControllerConstants;
import eaa.tgi.scrum.domain.StoredFile;
import eaa.tgi.scrum.domain.User;

@Controller
public class DropboxController {

	/**
	 * 
	 * @return
	 */
	@RequestMapping(ControllerConstants.HANDLE_DROPBOX)
	public ModelAndView displayDropbox(HttpServletRequest request) {
		
		User user = (User) request.getSession().getAttribute("authenticatedUser");
		
		ModelAndView modelView = new ModelAndView();
		
		List<StoredFile> fileList = user.getProject().getFileList();		
		modelView.addObject("fileList", fileList);
		
		modelView.setViewName(ControllerConstants.JSP_DROPBOX);
		
		return modelView;
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(ControllerConstants.HANDLE_UPLOAD_FILE)
	public ModelAndView uploadFile(HttpServletRequest request) {
		
		ModelAndView modelView = new ModelAndView();
		modelView.setViewName(ControllerConstants.JSP_DROPBOX);

		try {

			User user = (User) request.getSession().getAttribute("authenticatedUser");

			DiskFileUpload fileUpload = new DiskFileUpload();

			List<FileItem> fileItems = fileUpload.parseRequest(request);

			for(FileItem item : fileItems) {

				if(item.getFieldName().equals("Filedata")) {

					StoredFile fileToBeStored = new StoredFile();
					fileToBeStored.setFilesize(item.getSize());
					fileToBeStored.setFile(item.get());
					fileToBeStored.setFilename(item.getName());
					fileToBeStored.setUploadDate(new Date());
					fileToBeStored.setProjectId(user.getProject().getId());
					fileToBeStored.setOwner(user.getUsername());

					user.getProject().store(fileToBeStored);
				}
			}

		} catch(Exception e) {
			modelView.addObject(ControllerConstants.ERROR_MESSAGE, "Erro ao enviar arquivo");	
		}

		return modelView;
	}
	
	/**
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping(ControllerConstants.HANDLE_FILE_LIST)
	public ModelAndView fileList(HttpServletRequest request) {
		
		ModelAndView modelView = new ModelAndView();
		modelView.setViewName("filelist.jsp");
		
		User user = (User) request.getSession().getAttribute("authenticatedUser");
		
		List<StoredFile> fileList = user.getProject().getFileList();		
		modelView.addObject("fileList", fileList);
		
		return modelView; 		
	}
}
